﻿using CKS.Core.Framework.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKS.Core.Framework
{
    public static class WinApp
    {

        //public static HostApplicationBuilder CreateHostBuilder(bool useAppsettings = false)
        //{

        //    var configBuilder = new ConfigurationBuilder()
        //        .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "config")) // 设置配置文件所在目录
        //        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); // 加载配置文件

        //    var config = configBuilder.Build();
        //    var builder = Host.CreateApplicationBuilder();
        //    if(useAppsettings)
        //        builder.Configuration.AddConfiguration(config);
            
        //    return builder;

        //}


        public static ServiceCollection AddFreesql(this ServiceCollection services)
        {
            var mesdb = Configs.GetConnectionString("MesDB");
            FreeSql.DataType dataType = FreeSql.DataType.MySql;
            switch (mesdb.dbType)
            {
                case 0:
                    dataType = FreeSql.DataType.MySql;
                    break;
                case 1:
                    dataType = FreeSql.DataType.SqlServer;
                    break;
                default:
                    break;
            }

         

            #region Freesql注入

            Func<IServiceProvider, IFreeSql<MesDB>> fsqlFactory = r =>
            {

                IFreeSql<MesDB> fsql = new FreeSql.FreeSqlBuilder()
                    .UseConnectionString(dataType, mesdb.connectionString)
                    //.UseMonitorCommand(cmd => Debug.WriteLine($"Sql：{cmd.CommandText}"))//监听SQL语句
                    // .UseAutoSyncStructure(true) //自动同步实体结构到数据库，FreeSql不会扫描程序集，只有CRUD时才会生成表。

                    .UseMonitorCommand(cmd => {
                        if (cmd.CommandTimeout <= 1200)
                            cmd.CommandTimeout = 1200; //超时时间统一设置成 1200秒（20分钟）
                    }, null)
                    .Build<MesDB>();
                return fsql;
            };
            services.AddTransient<IFreeSql<MesDB>>(fsqlFactory);

            #endregion


            return services;
        }


       
    }
}
